package HashTable;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-07-05
 * Time: 9:15
 */
public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    public Node[] array;
    public int usedSize;//当前存放的数据元素的个数
    private static final double LOAD_FACTOR=0.75;
    public HashBuck(){
        this.array=new Node[8];
    }
    public void put(int key,int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        /**
         * 遍历index下标的链表
         * 1.查看是否有一样的key
         * 2.没有的话 进行头插法
         */
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;

            }
            cur = cur.next;
        }
        node.next=array[index];
        array[index]=node;
        usedSize++;
        //检查当前哈希表是否超过负载因子
        if(loadFactor()>=LOAD_FACTOR){
            //扩容
            resize();
        }
    }
    private void resize(){//扩容要注意重新哈希
        Node[] tmp=new Node[2* array.length];
        for(int i=0;i<array.length;i++){
            Node cur=array[i];
            while(cur!=null){
                Node curNext=cur.next;
                int index=cur.key%tmp.length;
                cur.next=tmp[index];
                tmp[index]=cur;
                cur=curNext;
            }
        }
        array=tmp;
    }
    private double loadFactor(){
        return 1.0*usedSize/ array.length;
    }
    public int get(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
